import { Device, GatewayType } from "@/api/interface/iot";
import { copyProduct, getProduct, modifyProduct, syncFromProduct } from "@/api/modules/iot/product";
import { getProfile } from "@/api/modules/model/profile";
import { getSchema } from "@/api/modules/model/schema";
import PageHeader from "@/components/Frame/PageHeader";
import { SchemaItem } from "@/components/JsonSchemaForm/interface";
import JsonView from "@/components/Sansan/Model/develop/PrviewSchemaJson";
import DeviceParam from "@/components/Sansan/Model/device/DeviceParam";
import FuncList from "@/components/Sansan/Model/device/FuncList";
import SensorList from "@/components/Sansan/Model/device/SensorFormList";
import FuncConfig from "@/components/Sansan/Model/gateway/FuncConfig";
import GatewayConfig from "@/components/Sansan/Model/gateway/GatewayConfig";
import BasicConfig from "@/components/Sansan/Model/product/BasicConfig";
import Navigation from "@/components/Sansan/Model/product/Navigation";
import ViewConfig from "@/components/Sansan/Model/product/ViewConfig";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import router from "@/routers";
import { IotStore } from "@/stores/modules/iot";
import { AuthBtns, CommonText, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import SaveToProduct from "./components/SaveToProduct";
import SimpleInfo from "./components/SimpleInfo";
import BasicDialog from "./components/basicInfo/detailDialog";
import ExtLower from "@/components/Sansan/Model/gateway/extLower";
import "./product.scss";
import { ComponentInternalInstance, getCurrentInstance, ref } from "vue";
import { productModel } from "@/enums/dictEnum";
import { isRootDeptId } from "@/utils/format";

export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const iotStore = IotStore();
		let menuId = AuthBtns.iotProduct;
		//产品schema
		const schemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.schema, schemaInfo);
		provide(SchemaNodeKey.gatewaySchema, schemaInfo);

		//产品profile
		const prifileInfo = ref<any>({});
		provide(SchemaNodeKey.profile, prifileInfo);
		provide(SchemaNodeKey.gatewayProfile, prifileInfo);

		//产品详情
		const detail = reactive({ detail: {} as Device.ResProduct });
		provide(SchemaNodeKey.detailInfo, detail);
		const disabledMod = ref(true);
		provide(AuthBtns.disabledMod, disabledMod);
		const buttonsList = ref<any>([]);
		mittBus.on("refreshProductDetail", () => {
			init();
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshProductDetail");
		});
		onMounted(async () => {
			init();
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons(menuId as string);
			disabledMod.value =
				!!isRootDeptId([detail.detail]) || !buttonsList.value.some((item: any) => item.path == AuthBtns.pathMod);
		});
		const init = async () => {
			await initIotData();
			await initProfile();
			await initSchema();
		};
		//初始化产品信息
		const initIotData = async () => {
			let { result, code } = await getProduct({
				id: route.query.id as string,
				productModel: route.query.productModel
			});
			if (code == 200) {
				detail.detail = result;
				route.query.productModel = result.model;
				route.query.id = result.id;
			} else {
				showMsg(proxy?.$t("productdialog.msg.nodata"), MessageType.error);
				if (window.frames.length != parent.frames.length) return;
				timeOut.value = setTimeout(() => {
					router.go(-1);
				}, 3000);
			}
		};
		//未找到设备数据时三秒后返回上级页面
		let timeOut = ref();
		//销毁定时器
		onBeforeUnmount(() => {
			clearInterval(timeOut.value);
			timeOut.value = "";
		});
		const initSchema = async () => {
			const { result } = await getSchema({ productModel: route.query.productModel });
			schemaInfo.value = result?.schema || { props: {} };
		};
		const initProfile = async () => {
			const { result } = await getProfile({ productId: route.query.id });
			prifileInfo.value = result?.profile || {};
		};

		const currNav = ref<string>("");
		const basicDialog = reactive({
			title: proxy?.$t("productdialog.dialog_title.modify"),
			visible: false
		});
		const changeNav = (nav: string) => {
			currNav.value = nav;
		};
		const submitBasic = async (info?: Device.ResProduct) => {
			info = info || detail.detail;
			let { success } = await modifyProduct({ ...info });
			if (success) {
				ElMessage.success(proxy?.$t("productdialog.elmsg.success"));
				basicDialog.visible = false;
				initIotData();
			} else {
				ElMessage.error(proxy?.$t("productdialog.elmsg.fali"));
			}
		};
		//停止、启动产品
		const handerBtn = async (type: string) => {
			switch (type) {
				case "copy":
					copyProductDialog.visible = true;
					copyProductDialog.formData = JSON.parse(JSON.stringify(detail.detail));
					break;
				case "syncFromProduct":
					confirm({ content: proxy?.$t("productdialog.confirm.sync_from_product") }).then(flag => {
						if (!flag) {
							return;
						}
						syncFromProduct({ productModel: detail.detail.model }).then(({ code }) => {
							showTips(code, proxy?.$t("productdialog.tips.sync"));
						});
					});
					break;
			}
		};
		const copyProductDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const submitCopyProduct = async (data: Device.ResProduct) => {
			let { code, result, message } = await copyProduct(data);
			let ok = showTips(code, proxy?.$t("productdialog.tips.copy"), message);
			if (ok) {
				copyProductDialog.visible = false;
				result && router.push({ path: RouterPath.productDetail, query: { id: result.id, productModel: result.model } });
			}
		};
		const showProduct = ref(false);
		const viewType = computed(() => {
			let item: any = detail.detail.view?.page?.find(info => Object.values(info)[0] as any);
			let page: any = (item && Object.values(item)[0]) || {};
			return page.url;
		});
		// 动态引入 @/components/Sansan/Model/views 路径下所有组件
		// 注意 组件必须要有名字，否则过滤掉
		const modulesFiles = import.meta.glob("@/components/Sansan/Model/views/**/*.tsx", { eager: true });
		const modulesFiles1 = import.meta.glob("@/components/Sansan/Model/views/**/*.tsx");
		let comList = {} as any;
		comList = markRaw(comList);
		Object.keys(modulesFiles).forEach(item => {
			let comp = modulesFiles[item] as any;
			let name = comp.default.name;
			if (name) {
				comList[name] = defineAsyncComponent(modulesFiles1[item] as any);
			}
		});
		let componentsList = ref(comList);
		return () => {
			return (
				<div class="product-detail-page">
					{iotStore.isMaxDetail ? null : (
						<>
							<PageHeader
								showBackText={false}
								v-slots={{
									operate: () => {
										return (
											<>
												{/* 显示模式：配置模式、数据可视化模式 */}
												{false && viewType.value ? (
													<el-button
														onClick={() => {
															showProduct.value = !showProduct.value;
														}}
													>
														{showProduct.value ? CommonText.configView : CommonText.dataView}
													</el-button>
												) : null}
												{buttonsList.value.map((item: any) => {
													return item.path == "syncFromProduct" || item.path == "copy" ? (
														<el-button class={["iconfont", item.btnClass]} onClick={() => handerBtn(item.path)}>
															{item.menuName}
														</el-button>
													) : null;
												})}
												{!disabledMod.value && (
													<el-button type="primary" class="iconfont iconedit" onClick={() => (basicDialog.visible = true)}>
														{proxy?.$t("productdialog.btn.modify")}
													</el-button>
												)}
												{/* <SaveClearBtn v-model={basicDialog.visible} /> */}
											</>
										);
									}
								}}
							>
								<span>{detail.detail.name || detail.detail.model}</span>
								<el-link
									class="iconfont iconbx-sync ml-2"
									type="primary"
									onClick={() => {
										init();
									}}
								>
									{proxy?.$t("common.btn.refresh")}
								</el-link>
							</PageHeader>
							<SaveToProduct
								title={proxy?.$t("productdialog.dialog_title.copy")}
								v-model:visible={copyProductDialog.visible}
								formData={copyProductDialog.formData}
								onSubmit={(data: Device.ReqProduct) => submitCopyProduct(data)}
							></SaveToProduct>
							<BasicDialog
								title={basicDialog.title}
								v-model:visible={basicDialog.visible}
								width="800px"
								detail={detail.detail}
								onSubmit={() => {
									submitBasic();
								}}
							></BasicDialog>
						</>
					)}
					{!viewType.value || !showProduct.value ? (
						<>
							{iotStore.isMaxDetail ? null : (
								<div class="mb-4 p-4 bg-white ">
									{/* 基本信息：名称、分组、产品 */}
									<SimpleInfo visible={basicDialog.visible} />
								</div>
							)}

							<div class="iot-detail-content">
								{/* 导航分类：基本信息、产品参数、产品模型、产品日志 */}
								<Navigation onChange={val => changeNav(val)} deviceType={detail.detail.deviceType} />

								<div class="bg-white detail-type-detail">
									{/*基本信息*/}
									{currNav.value == SchemaNodeKey.basic ? <BasicConfig /> : ""}

									{/*网关接入配置*/}
									{currNav.value == SchemaNodeKey.extNavGatewayConfig ? <GatewayConfig type={GatewayType.Product} /> : ""}

									{/*产品配置信息--接入地址、接入端口*/}
									{/* {currNav.value == SchemaNodeKey.extNavDeviceConfig ? <DeviceConfig type={GatewayType.Product} /> : ""} */}

									{/*产品变量配置--变量字段描述*/}
									{/* {currNav.value == SchemaNodeKey.extNavSensorConfig ? <SensorConfig type={GatewayType.Product} /> : ""} */}
									{/* 下位机 */}
									{currNav.value == SchemaNodeKey.extLower ? <ExtLower /> : null}

									{/*产品功能配置--变量字段描述*/}
									{currNav.value == SchemaNodeKey.extNavFuncConfig ? <FuncConfig type={GatewayType.Product} /> : ""}

									{/*设备模型*/}
									{currNav.value == SchemaNodeKey.extDevelop ? <JsonView type={detail.detail.deviceType} /> : null}
									{/*设备配置信息--接入地址、接入端口*/}
									{currNav.value == SchemaNodeKey.config ? <DeviceParam type={GatewayType.Gateway} /> : null}

									{/*产品模型*/}
									{currNav.value == SchemaNodeKey.sensor ? <SensorList type={GatewayType.Gateway} /> : null}
									{currNav.value == SchemaNodeKey.funcs ? <FuncList type={GatewayType.Gateway} /> : null}

									{/*产品可视化 */}
									{currNav.value == SchemaNodeKey.view ? (
										<ViewConfig product={detail.detail} disabled={disabledMod.value} onSubmit={submitBasic} />
									) : null}
								</div>
							</div>
						</>
					) : (
						<>
							{/* 使用动态可视化組件 */}
							{viewType.value
								? h(componentsList.value[viewType.value], {
										is6210: detail.detail.model == productModel.ss6210,
										isHmp: detail.detail.model == productModel.hmp
								  })
								: null}
						</>
					)}
				</div>
			);
		};
	}
});
